package web.controller;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import entities.PersonSheet;
import entities.Sheet;

import service.authentification.Authentificator.Reg;
import service.authentification.IAuthentificator;
import service.configuration.IConfiguration;
import service.configuration.NamingUtil;
import service.sheetmanager.ISheetManager;
import web.form.RegisterForm;

/**
 * <b>RegisterController  </b>
 * <p>RegisterController controle les requêtes pour le service d'inscription.</p>
 * 
 */
@Controller
public class RegisterController {
	
	/**
     * Repr&eacute;sente le service d'authentification
     */
	@Resource
	private IAuthentificator auth;
	
	/**
     * Repr&eacute;sente le service de configuration
     */
	@Resource
	private IConfiguration configuration;
	
	/**
     * Repr&eacute;sente le service de gestion de fiches
     */
	@Resource
	private ISheetManager sheetManager;
	
	/**
     * Controlleur qui renvoi la page d'inscription
     */
	@RequestMapping(value = "/register.htm", method = RequestMethod.GET)
	public String handleRequestRegister(@RequestHeader("Referer") String referer,
			HttpSession session, ModelMap model)  {
		
		if(referer!=null){
			RegisterForm registerForm = new RegisterForm();
			model.addAttribute("registerForm",registerForm);
			return "register";
		}else{
			return "redirect : treeview.htm";
		}
			
	}
	
	/**
     * Controlleur qui recoi une requête pour inscrire un utilisateur via le service d'authentificaiton
     */
	@RequestMapping(value = "/register.htm", method = RequestMethod.POST)
	public String onSubmitRegister(@RequestHeader("Referer") String referer,HttpSession session, 
								@ModelAttribute("registerForm") RegisterForm form,
								BindingResult result, ModelMap model) throws Exception {
		
		Reg success = auth.register(form.getCode());
		if(success.getMail()==null)
			success.setMail("vide");
		JSONObject json = new JSONObject();
		switch (success.getStatus()) {
			case 0:{
				json.put("success", false);
				json.put("message", "Ce nom n'est pas reconnu par le système.");
				break;
			}
			case 1:{
				json.put("success", false);
				json.put("message", "Vous êtes dèja inscrit");
				break;
			}
			case 2:{
				json.put("success", true);
				json.put("message", "Vous êtes bien inscrit.<br/>Un message est envoyé vers votre boite mail :<br/>"+success.getMail()+" .");
				break;
			}
			
		}
			
		model.addAttribute("jsonArray", json);
		return "json";
	}
	
	/**
     * Controlleur qui renvoi la liste des individus au format JSON pour l'autocomplétion des noms
     */
	@RequestMapping(value = "/autocomplete.htm", method = RequestMethod.GET)
	public String onSubmitAutoComplete(HttpSession session,
			@RequestParam(value="callback", required=false) String callback,
			@RequestParam(value="name_startsWith", required=false) String Name,
			ModelMap model) throws JSONException {
		
		List <Sheet> list=sheetManager.findSheetsByPropertyLike(NamingUtil.LASTNAME, Name, configuration.getPersonType());
		
		JSONObject jsonp = new JSONObject();
		JSONArray personsList = new JSONArray();
		
		jsonp.put("totalResultsCount", list.size());
		
		for (Sheet person : list){
			personsList.put(new JSONObject().put("personFirstName", ((PersonSheet)person).getFirstName()).put("personLastName", ((PersonSheet)person).getLastName()).put("personCode", ((PersonSheet)person).getCode()).put("personId", ((PersonSheet)person).getLdap()));
		}
		
		jsonp.put("persons", personsList);
		
		if (callback != null){
			model.addAttribute("callback", callback);
		}
		model.addAttribute("jsonArray", jsonp);
		
		return "json";
	}
}